<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\SendWechatTemplate;
use App\Models\Book;
use App\Models\BookComment;
use App\Models\OrderItem;
use App\Models\User;
use Illuminate\Http\Request;
use function Sodium\increment;

class BookCommentController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function index(Request $request)
    {
        $book_id      = intval($request->get('book_id',1));
        $list = BookComment::query()->where('type',1)->where('deleted',0)->where('book_id',$book_id)->orderBy('id','desc')->get();
        $items = [];
        if(!empty($list))
        {
            foreach ($list as $item)
            {
                $items[] = [
                    'id'            => $item->id,
                    'user_id'       => $item->user_id,
                    'user_nickname' => $item->user_nickname,
                    'user_avatar'   => $item->user_avatar,
                    'content'       => $item->content,
                    'score'         => $item->score,
                ];
            }
        }
        $data = [
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function store(Request $request)
    {
        $book_id = intval($request->get('book_id'));
        $user_id = intval($request->get('user_id'));
        $score = intval($request->get('score'));
        $content = trim($request->get('content'));

        if(empty($book_id) || empty($user_id) || empty($content))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::find($user_id);
        if(empty($user))
        {
            return $this->err(1,200,'','用户不存在');
        }

        $book = Book::find($book_id);
        if(empty($book))
        {
            return $this->err(1,200,'','图书不存在');
        }

        //增加评论数量
        $book->addCommentNum();

        $comment   = new BookComment([
            'type'          => 1,
            'user_id'       => $user_id,
            'user_nickname' => $user->wechat_nickname,
            'user_avatar'   => $user->wechat_avatar,
            'score'         => $score,
            'content'       => $content,
            'created_at'    => $this->time,
            'updated_at'    => $this->time
        ]);
        $comment->book()->associate($book);
        $comment->save();

        return $this->ok([],'添加成功');
    }

    public function destroy(Request $request)
    {
        $id = intval($request->get('id'));
        if(empty($id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $comment = BookComment::find($id);

        if(!$comment->deleted)
        {
            $comment->update([
                'deleted'      => 1,
                'deleted_at'   => $this->time
            ]);

            $book = Book::find($comment->book_id);
            $book->decreaseCommentNum();
            return $this->ok([],'删除成功');
        }

        return $this->err(1,200,'','删除失败');
    }

    public function getList(Request $request)
    {
        $page      = intval($request->get('page',1));
        $page      = max($page ,1);
        $page_size = intval($request->get('limit',10));
        $type      = intval($request->get('type')); //0全部 1待审核 2审核通过 3审核未通过

        $builder = BookComment::query()->with(['book'])->where('deleted',0)->where('type',2);

        if($type)
        {
            if($type == 1)
            {
                $builder->where('state',0);
            }
            elseif($type == 2)
            {
                $builder->where('state',1);
            }
            elseif($type == 3)
            {
                $builder->where('state',2);
            }
        }
        $columns = ['id','user_nickname','user_avatar','created_at','state','book_id','user_id'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'                => $item['id'],
                    'user_id'           => $item['user_id'],
                    'user_nickname'     => $item['user_nickname'],
                    'user_avatar'       => $item['user_avatar'],
                    'created_at'        => $item['created_at'],
                    'content'           => $item['content'],
                    'created_at_str'    => date('Y-m-d H:i:s',$item['created_at']),
                    'state'             => $item['state'],
                    'book_id'           => $item['book_id'],
                    'book_title'        => $item->book->title,
                    'book_image'        => $item->book->image,
                    'book_author'       => $item->book->author,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $id = intval($request->get('id'));
        if(empty($id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $comment = BookComment::query()->with(['book'])->where('id',$id)->first();
        if(empty($comment))
        {
            return $this->err(1,200,'','书评不存在');
        }

        $result = [
            'id'                => $comment['id'],
            'user_nickname'     => $comment['user_nickname'],
            'user_avatar'       => $comment['user_avatar'],
            'created_at'        => $comment['created_at'],
            'created_at_str'    => date('Y-m-d H:i:s',$comment['created_at']),
            'state'             => $comment['state'],
            'book_id'           => $comment['book_id'],
            'content'           => $comment->content,
            'book_title'        => $comment->book->title,
            'book_image'        => $comment->book->image,
            'book_author'       => $comment->book->author,
        ];
        return $this->ok($result);
    }

    public function updateState(Request $request)
    {
        $id     = intval($request->get('id'));
        $state  = intval($request->get('state'));

        if(empty($id) || empty($state) || !in_array($state,[1,2]))
        {
            return $this->err(1,200,'','参数错误');
        }

        $comment = BookComment::query()->with(['book'])->where('id',$id)->first();
        if(empty($comment))
        {
            return $this->err(1,200,'','书评不存在');
        }

        if($state == 1)
        {
            //审核通过
            //使用异步队列
            $job_params = [
                'user_id'           => $comment->user_id,
                'template_id'       => 'a2hKb0lOF-B9zAFMd9bR6aW0Zj0nS6UaXsWBGX8jqO4',
                'book_id'           => $comment->book_id,
            ];
            dispatch(new SendWechatTemplate($job_params));

            Book::query()->where('id',$comment->book_id)->increment('comment_num');
        }

        OrderItem::query()->where('id',$comment->order_items_id)->update(['review_state'=>$state]);
        $comment->update([
            'state'         => $state,
            'updated_at'    => $this->time
        ]);
        return $this->ok([],'操作成功');
    }

}
